package com.example.mybatisplusdemo.handler;

import com.example.mybatisplusdemo.Result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({ConstraintViolationException.class, BindException.class})
    public Result validateException(Exception e, HttpServletRequest request) {
        String msg = null;
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations();
            ConstraintViolation<?> next = violations.iterator().next();
            msg = next.getMessage();
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            msg = bindException.getBindingResult().getFieldError().getDefaultMessage();
        }
        return new Result(400,msg);
    }
}
